#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <map>

using namespace std;

typedef long long ll;

template <typename T> inline void read(T &r){
    char c;bool f=0;
    for(c=getchar();c>'9'||c<'0';c=getchar()) if(c=='-') f=1;
    for(r=0;c<='9'&&c>='0';c=getchar()) r=r*10+c-'0';
    if(f) r=-r;
}

template <typename T> void write(const T &t){
    if(t<0) putchar('-'),write(-t);
    else{
        if(t>9) write(t/10);
        putchar(t%10+'0');
    }
}

template <typename T> T exgcd(const T &a,const T &b,T &x,T &y){
    if(b){
        T g=exgcd(b,a%b,x,y);
        T t=x;x=y;y=t-a/b*y;
        return g;
    }else{
        x=1;y=0;
        return a;
    }
}

template <typename T> T inv(T a,T p){
    T x,y;
    exgcd(a,p,x,y);
    return (x%p+p)%p;
}

int main(){
    int T;

    freopen("exercise.in","r",stdin);
    freopen("exercise.out","w",stdout);

    read(T);
    while(T--){
        ll x,n,a,b,c,d,p;
        read(x);read(a);read(b);read(c);read(d);read(n);read(p);
        map<ll,int> mp;
        int cnt=0;
        while(1){
            mp[x]=cnt++;
            //printf("%I64d ",x);
            x=(a*x+b)*inv(c*x+d,p)%p;
            //x=(a*x+b)/(c*x+d)%p;
            if(mp.count(x)) break;
        }
        //putchar('\n');
        int len=cnt-mp[x];
        n=(n-mp[x])%len+mp[x];
        for(map<ll,int>::iterator it=mp.begin();it!=mp.end();it++){
            if(it->second==n){
                write(it->first);putchar('\n');
                break;
            }
        }
    }
    return 0;
}
